﻿Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO
Public Class clsCryptoUtil
    Private Const sKey As String = "qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3"
    Private Const sIV As String = "poiuytre"
    Private Shared mCSP As SymmetricAlgorithm = New TripleDESCryptoServiceProvider()

    ''' <summary>
    ''' 輸入要加密的字串,回傳加密後的字串
    ''' </summary>
    ''' <param name="inTXT"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function Encrypt(ByVal inTXT As String) As String
        Try
            Dim ct As ICryptoTransform
            Dim ms As MemoryStream
            Dim cs As CryptoStream
            Dim byt As Byte()

            mCSP.Key = Convert.FromBase64String(sKey)
            mCSP.IV = ASCIIEncoding.ASCII.GetBytes(sIV)
            '//指定加密的運算模式
            mCSP.Mode = System.Security.Cryptography.CipherMode.CBC
            '//獲取或設置加密算法的填充模式
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7
            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV) '//建立加密對象
            byt = Encoding.UTF8.GetBytes(inTXT)
            ms = New MemoryStream()
            cs = New CryptoStream(ms, ct, CryptoStreamMode.Write)
            cs.Write(byt, 0, byt.Length)
            cs.FlushFinalBlock()
            cs.Close()
            Return Convert.ToBase64String(ms.ToArray())
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function


    ''' <summary>
    ''' 輸入加密的字串,回傳解密後的字串
    ''' </summary>
    ''' <param name="inEncryString"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function Decrypt(ByVal inEncryString As String) As String
        Dim ct As ICryptoTransform '//加密轉換運算
        Dim ms As MemoryStream '//內存流
        Dim cs As CryptoStream '//數據流連接到數據加密轉換的流
        Dim byt As Byte()
        Try

            '//將3DES的密鑰轉換成byte
            mCSP.Key = Convert.FromBase64String(sKey)
            '//將3DES的向量轉換成byte
            mCSP.IV = ASCIIEncoding.ASCII.GetBytes(sIV)
            mCSP.Mode = System.Security.Cryptography.CipherMode.CBC
            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7
            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV) '//建立對稱解密對象
            byt = Convert.FromBase64String(inEncryString)
            ms = New MemoryStream()
            cs = New CryptoStream(ms, ct, CryptoStreamMode.Write)
            cs.Write(byt, 0, byt.Length)
            cs.FlushFinalBlock()
            cs.Close()
            Return Encoding.UTF8.GetString(ms.ToArray())
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function

End Class
